package 网络编程.homework;

import 网络编程.utils.StreamUtils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author Y·C
 * @version 1.0.0
 * @ClassName Homework03Client.java
 * @Description TODO
 * @createTime 2023年05月04日 16:26:00
 */
public class Homework03Client {
    public static void main(String[] args) throws Exception {
        //1.接受用户输入，指定下载文件名
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入下载文件名");
        String downloadFileName = scanner.next();

        //2.客服端连接服务器，准备发送
        Socket socket = new Socket(InetAddress.getLocalHost(), 9999);
        //3. 获取和Socket关联的输出流
        OutputStream outputStream = socket.getOutputStream();
        outputStream.write(downloadFileName.getBytes());
        //设置写入结束标志
        socket.shutdownOutput();

        //4.读取服务端返回的文件（字节数据）
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());

        byte[] bytes = StreamUtils.streamToByteArray(bis);
        //5.得到一个输出流，准备将bytes写入到磁盘文件
        String filePath = "D:\\files\\f\\" + downloadFileName + ".png";
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(filePath));
        bos.write(bytes);

        //关闭资源
        bos.close();
        bis.close();
        socket.close();
        outputStream.close();

        System.out.println("客服端下载完毕，正确退出");
    }
}
